package com.epam.qanda.web.servlet.moderator;

import java.io.IOException;
import java.sql.Date;
import java.util.Calendar;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.UserService;
import com.epam.qanda.mail.EmailUtility;

public class BanQuestionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");
	
    public BanQuestionServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer userId = Integer.parseInt(request.getParameter("usId"));
		Integer time = Integer.parseInt(request.getParameter("time"));
		UserService service = new UserService();
		User user = service.read(userId);
		Long currTime = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(currTime);
		if (time == 1) {
			calendar.add(Calendar.DAY_OF_YEAR, +1);
		} else if (time == 2) {
			calendar.add(Calendar.WEEK_OF_YEAR, +1);
		} else if (time == 3) {
			calendar.add(Calendar.MONTH, +1);
		} else if (time == 4) {
			calendar.add(Calendar.YEAR, +1);
		} else if (time == 5) {
			user.setStatus(true);
			user.setDateBanOff(null);
			service.update(user);
			try {
				new EmailUtility().sendEmail("Quanda Ban", "You baned permanent", user);
			} catch (MessagingException e) {
				LOG.warn(e.getMessage());
			}
			return;
		}
		user.setStatus(true);
		Date date = new Date(calendar.getTimeInMillis());
		user.setDateBanOff(date);
		service.update(user);
		try {
			new EmailUtility().sendEmail("Quanda Ban", "<h4 style=color:red;>You baned until </h4>" + date.toString(), user);
		} catch (MessagingException e) {
			LOG.warn(e.getMessage());
		}
		
	}

}
